/* 
 * File:   State.cxx
 * Author: enric
 * 
 * Created on 26 de enero de 2012, 18:58
 */

#include "State.hxx"

char eShape2char( eShape s )
{
	switch( s )
	{
	case star: return '*';
	case plus: return '+';
	case minus: return '-';
	case slash: return '/';
	default: return ' ';
	}
}

State::State()
	: m_agent(NULL)
{}

State::State( State* s )
{
    for ( unsigned k = 0; k < s->cells().size(); k++ )
            m_world_cells.push_back( new Cell( s->cells()[k] ) );

    for ( unsigned k = 0; k < s->keys().size(); k++ )
    {
            Cell* new_key_loc = m_world_cells[ s->keys()[ k ]->location()->identifier() ];
            m_keys.push_back( new Key( s->keys()[k]->identifier(), s->keys()[k]->shape(), new_key_loc ) );
    }

    Cell* new_agent_loc = m_world_cells[ s->agent()->location()->identifier() ];
    m_agent = new Agent( new_agent_loc );
    if( ! s->agent()->arm_empty() )
            m_agent->set_key_holding( m_keys[ s->agent()->key_holding()->identifier() ] );
    else
            m_agent->set_key_holding( NO_KEY );
}

State::~State()
{
	for ( unsigned k = 0; k < m_world_cells.size(); k++ )
		delete m_world_cells[k];
	for ( unsigned k = 0; k < m_keys.size(); k++ )
		delete m_keys[k];
	delete m_agent;
}

void State::setFather( State& father )
{
    this->m_father = &father;
}

std::string State::to_string()
{
	std::stringstream ss;

	for ( unsigned k = 0; k < m_world_cells.size(); k++ )
		if( m_world_cells[k]->locked() )
			ss << "\tCell at (" << m_world_cells[k]->x() << "," << m_world_cells[k]->y() << ") is locked "  << eShape2char( m_world_cells[k]->keyhole() )<< std::endl;
			
	ss << "\tAgent at (" << m_agent->location()->x() << "," << m_agent->location()->y() << ") ";
	if( ! m_agent->arm_empty() )
		ss << "holding( k"<< m_agent->key_holding()->identifier()<< " )";
	ss << std::endl;
	
	for ( unsigned k = 0; k < m_keys.size(); k++ )
		ss << "\tKey" << k << " at (" << m_keys[k]->location()->x() << "," << m_keys[k]->location()->y() << ") " << eShape2char( m_keys[k]->shape() )<< std::endl;
	

	return ss.str();
}
